#define _LOGGER_INIT_
#include "LogWrapper.h"
#include "XFtpSessionFactory.h"
#include "XThreadPool.h"
#include <event2/event.h>
#include <event2/util.h>
#include <event2/listener.h>

#ifdef _WIN32
#include<winsock2.h>
#endif

#define PORT (21)

static void listener_cb(struct evconnlistener *e, evutil_socket_t fd,
    struct sockaddr * addr, int socklen, void *param) 
{
    LOG_INFO("new user connect");
    XTask *task = XFtpSessionFactory::get()->createTask(fd);
    XThreadPool::get()->dispatch(task);
}

int main(int argc, char *argv[])
{
#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    LOG_INFO("MiniFtp Start....");
    XThreadPool::get()->init(4);

    event_base * base = event_base_new();
    if (!base) {
        LOG_ERROR("failed to create event_base!");
        return -1;
    }
    sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);
    evconnlistener *ev = evconnlistener_new_bind(base,
        listener_cb,
        base,
        LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,
        10,
        (sockaddr *)&sin,
        sizeof(sin)
    );
    event_base_dispatch(base);
#ifdef _WIN32
    WSACleanup();
#endif
    getchar();
    return 0;
}